//
//  HQConversationViewController.m
//  Trip
//
//  Created by ISU1 on 16/3/14.
//  Copyright © 2016年 HQ. All rights reserved.
// 聊天列表

#import "HQConversationViewController.h"
#import "HQRCDataSource.h"
#import "RCDHttpTool.h"
#import "FriendViewController.h"

#import "AFHttpTool.h"
#import "HRMessageCell.h"
#import "HRMessage.h"
#import "HRGiftView.h"
#import "YD_purchaseCharms.h"

#import "HRGiftMessage.h"
#import "HRGiftMessageCell.h"
#import "HomeStrangCollionViewController.h"
#import "HRTextMessage.h"
#import "HRTextMessageCell.h"

//充值
#import "UserAccountViewController.h"

//收益
#import "UserEarningsController.h"


@interface HQConversationViewController()<RCMessageCellDelegate,CLLocationManagerDelegate,HRGiftViewDelegate,RCChatSessionInputBarControlDelegate> {
    int isFrist;
    NSString *longitude;
    NSString *latitude;
    NSString *address;
    NSString *_name;
    NSString *_distance;
    NSString *_currentLocation;
    
    NSInteger indexPathPage;
}

@property (nonatomic, strong) UILabel  *nameLabel;
@property (nonatomic, strong) HRGiftView *giftView;
@property (nonatomic, strong) UILabel  *placeLabel;
@property (strong, nonatomic) CLLocationManager * locationManger;
@property (nonatomic, strong) UIView *agreeView;
@property (nonatomic, strong) NSString *type;
@property (nonatomic, strong) NSString *wid;
@property (nonatomic, strong) NSString *herNickname;
@property (nonatomic, strong) UILabel *titleLabel;


/** 拉黑举报 */
@property (nonatomic, strong) UIButton *rightButton;
@property (nonatomic, strong) NSArray *reportArr;
/**
 判断是否为好友
 */
@property (nonatomic, strong) CheekisFriendModel *model;
/**
 添加好友
 */
@property (nonatomic, strong) UIButton *Addfriend;
@property (nonatomic, strong) UIButton *button;


@end

@implementation HQConversationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = Colorbackground;
    _reportArr = @[@"淫秽色情",@"政治反动",@"语言暴力",@"广告欺诈",@"虚假性别",@"其他内容",@"取消"];
    
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    self.chatSessionInputBarControl.pluginBoardView.backgroundColor = [UIColor whiteColor];
    [self.chatSessionInputBarControl.pluginBoardView insertItemWithImage:[UIImage imageNamed:@"message_gift_icon"] title:@"礼物" tag:101];
    [self.chatSessionInputBarControl.pluginBoardView updateItemAtIndex:0 image:[UIImage imageNamed:@"message_chat_picture_icon"] title:@"照片"];
    [self.chatSessionInputBarControl.pluginBoardView updateItemAtIndex:1 image:[UIImage imageNamed:@"message_chat_photo_icon"] title:@"拍照"];
        [self.chatSessionInputBarControl.pluginBoardView updateItemAtIndex:2 image:[UIImage imageNamed:@"Message_Location"] title:@"位置"];
    [self.chatSessionInputBarControl.pluginBoardView updateItemAtIndex:3 image:[UIImage imageNamed:@"message_voice_chat_icon2"] title:@"语音通话"];
    [self.chatSessionInputBarControl.pluginBoardView updateItemAtIndex:4 image:[UIImage imageNamed:@"message_viedo_chat_icon"] title:@"视频通话"];

    [self.chatSessionInputBarControl.pluginBoardView removeItemAtIndex:2];
    
    
    self.rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.rightButton setImage:[UIImage imageNamed:@"message_warn_circle_icon"] forState:UIControlStateNormal];
    self.rightButton.frame = CGRectMake(KScreenWidth-50, 25, 50, 30);
    [self.rightButton addTarget:self action:@selector(rightButtonClickAction) forControlEvents:UIControlEventTouchUpInside];
    
    if ([self.targetId isEqualToString:@"贴脸儿小助手"]) {
        
    }else{
        UIBarButtonItem *backItem = [[UIBarButtonItem alloc ] initWithCustomView:self.rightButton];
        self.navigationItem.rightBarButtonItem = backItem;
    }
   

    
    
    
    
    self.chatSessionInputBarControl.delegate = self;
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (kCLAuthorizationStatusDenied == status || kCLAuthorizationStatusRestricted == status) {
        [[DMCAlertCenter defaultCenter] postAlertWithMessage:@"当前定位权限没有打开"];
        //[self getFriendInfo];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    [self didLocation];
   
    self.enableSaveNewPhotoToLocalSystem = YES;
    [self setUpNav];
    
    [self registerClass:[HRMessageCell class]
        forMessageClass:[HRMessage class]];
    
    [self registerClass:[HRTextMessageCell class]
        forMessageClass:[HRTextMessage class]];
    
    [self registerClass:[HRGiftMessageCell class]
        forMessageClass:[HRGiftMessage class]];
}
/*!
 即将在聊天界面插入消息的回调
 
 @param message 消息实体
 @return        修改后的消息实体
 
 @discussion 此回调在消息准备插入数据源的时候会回调，您可以在此回调中对消息进行过滤和修改操作。
 如果此回调的返回值不为nil，SDK会将返回消息实体对应的消息Cell数据模型插入数据源，并在聊天界面中显示。
 */
- (RCMessage *)willAppendAndDisplayMessage:(RCMessage *)message {
    NSLog(@"message.objectName=========%@",message.objectName);
 
    if ([message.objectName isEqualToString:@"app:custom"]) {
        HRMessage *HRMsg = (HRMessage *)message;
        NSLog(@"content%@",HRMsg.content);
    }
    if ([message.objectName isEqualToString:@"app:GiftMessage"]) {
        HRGiftMessage *HRMsg = (HRGiftMessage *)message;
        NSLog(@"content%@",HRMsg.content);
        
    }
    return message;
}



#pragma mark ========设置聊天内容============
/*!
 即将显示消息Cell的回调
 
 @param cell        消息Cell
 @param indexPath   该Cell对应的消息Cell数据模型在数据源中的索引值
 
 @discussion 您可以在此回调中修改Cell的显示和某些属性。
 */
- (void)willDisplayMessageCell:(RCMessageBaseCell *)cell
                   atIndexPath:(NSIndexPath *)indexPath {

    RCMessageModel *model = self.conversationDataRepository[indexPath.item];

    if ([model.content isMemberOfClass:[HRTextMessage class]]) {
        
        HRTextMessage *TxtMsg = (HRTextMessage *)model.content;
        NSLog(@"extra 1 = %@",TxtMsg.extra);
        
        if ([TxtMsg.extra isEqualToString:@"hedadaTEexffs"]) {
 
        }
    }
    
    if ([model.content isMemberOfClass:[RCTextMessage class]]) {
        RCTextMessage *TxtMsg = (RCTextMessage *)model.content;
        NSLog(@"count 2 = %@",TxtMsg.content);
        
        if ([TxtMsg.content isEqualToString:@"我们已经是好友了，可以尽情聊天了"]) {
            _button.hidden = YES;
            self.chatSessionInputBarControl.hidden = NO;
        }
        
        NSLog(@"extra 2 = %@",TxtMsg.extra);
    }
    
    [super willDisplayMessageCell:cell atIndexPath:indexPath];
    
    if (indexPathPage == 1 ) {
        NSUInteger rowCount = [self.conversationMessageCollectionView numberOfItemsInSection:0];
        
        NSIndexPath* indexPath2 = [NSIndexPath indexPathForRow:rowCount-1 inSection:0];
        
        [self.conversationMessageCollectionView scrollToItemAtIndexPath:indexPath2 atScrollPosition:UICollectionViewScrollPositionBottom animated:NO];
        indexPathPage = 2;
    }

}
- (void)getFriendInfo {
    [AFHttpTool queryChatFriendInfoWithUid:[HQHttpManager getUserId] token:[HQHttpManager getUserToken] longitude:longitude latitude:latitude friendUid:self.targetId successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
        if (isSuccess) {
            _name = resultDic[@"res"][@"nickName"];
            _distance = [(NSNumber *)resultDic[@"res"][@"distance"] stringValue];
            _currentLocation = resultDic[@"res"][@"currentLocation"];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.nameLabel.text = _name;
                if ([_distance isEqualToString:@"-1"]) {
                    self.placeLabel.text = @"距离未知";
                } else {
                    self.placeLabel.text = [NSString stringWithFormat:@"距离您%@km,%@",_distance,_currentLocation];
                }
            });
        }
    }];
}
//是否为好有的请求在这里
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    indexPathPage  =  1;
    [self requestDateSoucebeFriend];
    
    self.navigationController.navigationBar.barTintColor =Colorbackground;
    
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc]init] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];
    self.navigationController.navigationBar.translucent = NO;
    
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor], NSFontAttributeName : FontP(18)};
    self.navigationController.navigationBarHidden = NO;
    if (self.conversationType == ConversationType_PRIVATE) {
        [RCDDataSource getUserInfoWithUserId:self.targetId completion:^(RCUserInfo *userInfo) {
            
            NSLog(@"self.targetId ===================%@",self.targetId);
            [RCDHTTPTOOL updateUserInfoByUid:[HQHttpManager getUserId]
                                       token:[HQHttpManager getUserToken]
                                   searchUid:self.targetId
                                     success:^(RCUserInfo *user) {
                                         [[RCIM sharedRCIM] refreshUserInfoCache:user withUserId:user.userId];
                                         [self.conversationMessageCollectionView reloadData];
                                     }
                                     failure:^(NSError *err) {
                                         
                                     }];
        }];
        
    }
   }

/**
 *  打开大图。开发者可以重写，自己下载并且展示图片。默认使用内置controller
 *
 *  @param imageMessageContent 图片消息内容
 */
//- (void)presentImagePreviewController:(RCMessageModel *)model {
//    RCImagePreviewController *_imagePreviewVC =
//    [[RCImagePreviewController alloc] init];
//    _imagePreviewVC.messageModel = model;
//    _imagePreviewVC.title = @"图片预览";
//    UINavigationController *nav = [[UINavigationController alloc]
//                                   initWithRootViewController:_imagePreviewVC];
//    [self presentViewController:nav animated:YES completion:nil];
//}
#pragma mark ===========判断是否为好友===========

-(void)requestDateSoucebeFriend{
    self.chatSessionInputBarControl.hidden = YES;
    if ([self.targetId isEqualToString:@"贴脸儿小助手"]) {
        self.chatSessionInputBarControl.hidden = NO;
        
    }else{
        [CheekVodeRequest getCheekVideoisFriendUid:[HQHttpManager getUserId] Wid:self.targetId success:^(id sucess) {
            _model = [CheekisFriendModel mj_objectWithKeyValues:sucess[@"res"]];

            if ([_model.status isEqualToString:@"0"]) {
                
                //先判断是否从好友变成陌生人  如果是。。。
                if ([_model.stranger isEqualToString:@"1"]) {
                    _Addfriend = [UIButton buttonWithType:UIButtonTypeCustom];
                    _Addfriend.frame =CGRectMake(0, self.conversationMessageCollectionView.bottom, KScreenWidth, 50);
                    [_Addfriend setImage:[UIImage imageNamed:@"message_link_follow_icon"] forState:UIControlStateNormal];
                    [_Addfriend setTitle:@"加为好友，才能聊天呦" forState:UIControlStateNormal];
                    [_Addfriend addTarget:self action:@selector(addFriendClick) forControlEvents:UIControlEventTouchUpInside];
                    _Addfriend.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
                    [_Addfriend setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                    _Addfriend.backgroundColor = [UIColor whiteColor];
                    [self.view addSubview:_Addfriend];
                }else{
                    //uid 判断是被动 还是主动方
                    if ([_model.uid isEqualToString:[HQHttpManager getUserId]] ) {
                        _Addfriend = [UIButton buttonWithType:UIButtonTypeCustom];
                        _Addfriend.frame =CGRectMake(0, self.conversationMessageCollectionView.bottom, KScreenWidth, 50);
                        [_Addfriend setImage:[UIImage imageNamed:@"message_link_follow_icon"] forState:UIControlStateNormal];
                        [_Addfriend setTitle:@"加为好友，才能聊天呦" forState:UIControlStateNormal];
                        [_Addfriend addTarget:self action:@selector(addFriendClick) forControlEvents:UIControlEventTouchUpInside];
                        _Addfriend.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
                        [_Addfriend setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                        _Addfriend.backgroundColor = [UIColor whiteColor];
                        [self.view addSubview:_Addfriend];
                    }else{
                        if ([_model.talkStatus isEqualToString:@"1"]) {
                            _button = [UIButton buttonWithType:UIButtonTypeCustom];
                            _button.frame =CGRectMake(0, self.conversationMessageCollectionView.bottom, KScreenWidth, 50);
                            [_button setImage:[UIImage imageNamed:@"message_chat_wait_icon"] forState:UIControlStateNormal];
                            [_button setTitle:@"等待对方添加你为好友" forState:UIControlStateNormal];
                            _button.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
                            [_button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                            _button.backgroundColor = [UIColor whiteColor];
                            [self.view addSubview:_button];
                        }else{
                            self.chatSessionInputBarControl.hidden = NO;
                        }
                    }
                }
            }else{
                
                self.chatSessionInputBarControl.hidden = NO;
                
                
            }
            
            
            
            
        } failure:^(NSError *error) {
            
        }];
    }
    
    
}
//加好友请求
- (void)addFriendClick{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber *numTemp = [numberFormatter numberFromString:self.targetId];

    [HQHttpManager pickWooWithUid:[HQHttpManager getUserId] wid:numTemp type:@(2) successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
        if (isSuccess) {
            
            _Addfriend.hidden = YES;
            _button.hidden = YES;
            self.chatSessionInputBarControl.hidden = NO;

            [self sendMessage:[RCTextMessage messageWithContent:@"我们已经是好友了，可以尽情聊天了"] pushContent:@"friend"];
        }
    }];
}
#pragma mark =====================拉黑 举报================
- (void)rightButtonClickAction{
//    [self.actionSheetTitle showGGActionSheet];
    
    HomeStrangCollionViewController *UDIVC = [[HomeStrangCollionViewController alloc] init];
    
    
    UDIVC.navigationController.navigationBar.hidden = YES;
    
    
    UDIVC.UserId = self.targetId ;
    [self.navigationController pushViewController:UDIVC animated:YES];
    
}

#pragma mark override
- (void)setUpNav {
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]  style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
    
    if (self.conversationType == ConversationType_GROUP) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"059_chat"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]  style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonClick)];
    } else if (self.conversationType == ConversationType_PRIVATE) {
//        UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kMainScreenWidth - 44 * 2, 44)];
//        
//        [titleView addSubview:self.nameLabel];
//        [titleView addSubview:self.placeLabel];
//        [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.centerX.mas_equalTo(0);
//            make.centerY.mas_equalTo(0);
//        }];
//        [self.placeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.mas_equalTo(self.nameLabel.mas_right).mas_equalTo(5);
//            make.top.mas_equalTo(self.nameLabel.mas_bottom).mas_equalTo(-5);
//        }];
//        self.navigationItem.titleView = titleView;
//        UIButton *rightBtn=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 25, 20)];
//        [rightBtn setImage:[UIImage imageNamed:@"more_img_hq"] forState:UIControlStateNormal];
//        [rightBtn addTarget:self action:@selector(rightButtonClick) forControlEvents:UIControlEventTouchUpInside];
//        self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    }
}
#pragma mark =========群==============
//- (void)rightButtonClick {
//    if (self.conversationType == ConversationType_GROUP) {
////        HQGroupInfoViewController *groupInfoVC = [HQGroupInfoViewController new];
////        groupInfoVC.conversationType = ConversationType_GROUP;
////        groupInfoVC.targetId = self.targetId;
////        groupInfoVC.targetGroupName = self.title;
////        [self.navigationController pushViewController:groupInfoVC animated:YES];
//    } else if
//        (self.conversationType == ConversationType_PRIVATE) {
////            NSArray *menuItems = @[[KxMenuItem menuItem:@"修改备注" image:[UIImage imageNamed:@"change_img_hq"] target:self action:@selector(changeRemarkName)],[KxMenuItem menuItem:@"删除" image:[UIImage imageNamed:@"delete_img_hq"] target:self action:@selector(deleteFriend)]];
////             CGRect targetFrame = self.navigationItem.rightBarButtonItem.customView.frame;
////            targetFrame.origin.y = targetFrame.origin.y + 34;
////            [KxMenu showMenuInView:self.navigationController.navigationBar.superview
////                          fromRect:targetFrame
////                         menuItems:menuItems];
//    }
//}
//- (void)changeRemarkName {
////    HQChangeRemarkNameViewController *changeRemarkVC = kVCFromSb(@"HQChangeRemarkNameViewController", @"Message");
////    changeRemarkVC.personId = self.targetId;
////    changeRemarkVC.pushViewController = ^(NSString * remarkName) {
////        self.nameLabel.text = remarkName;
////    };
////    [self.navigationController pushViewController:changeRemarkVC animated:YES];
//    
//}
- (void)deleteFriend {
       __weak typeof(self) __weakSelf = self;
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"删除后,将同时删除与该联系人的聊天记录" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action)
                                 {
                                     [RCDHTTPTOOL deleteFriendByUid:[HQHttpManager getUserId]
                                                              token:[HQHttpManager getUserToken]
                                                           friendId:self.targetId
                                                           complete:^(BOOL result)
                                      {
                                          if (result) {
                                              [[DMCAlertCenter defaultCenter] postAlertWithMessage:@"删除好友成功"];
                                              if (_pushViewController) {
                                                  _pushViewController(self.targetId);
                                              }
                                              [[RCIMClient sharedRCIMClient] removeConversation:ConversationType_PRIVATE targetId:self.targetId];
                                              [__weakSelf performSelector:@selector(backAction) withObject:nil afterDelay:1];
                                          } else {
                                              [[DMCAlertCenter defaultCenter] postAlertWithMessage:@"未能删除好友"];
                                          }
                                          
                                      }];
                                     
                                     
                                 }];
    [alertVC addAction:cancelAction];
    [alertVC addAction:sureAction];
    [__weakSelf presentViewController:alertVC animated:YES completion:nil];
}
- (void)backAction {
    for (UIViewController *temp in self.navigationController.viewControllers) {
        if ([temp isKindOfClass:[FriendViewController class]]) {
            NSString *Str = @"KNOTIFICATION_ReceiveMessage";
            [[NSNotificationCenter defaultCenter] postNotificationName:Str object:nil];
            [self.navigationController popToViewController:temp animated:YES];
            return;
        }
    }
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark 点击头像的回调
- (void)didTapCellPortrait:(NSString *)userId {
//    NSString *uid = [NSString stringWithFormat:@"%@",[LoginModel shareInstance].uid];
//    if (![uid isEqualToString:userId]) {
//        HQAddFriendViewController *friendVC =  kVCFromSb(@"HQAddFriendViewController", @"Message");
//        HQUserInfo *userInfo = [HQUserInfo new];
//        userInfo.userId = userId;
//        userInfo.portraitUri = @"";
//        userInfo.name = @"";
//        friendVC.targetUserInfo = userInfo;
//        [self.navigationController pushViewController:friendVC animated:YES];
//    } else {
//        MyViewController *myVC = kVCFromSb(@"MyViewController", @"PersonalCenter");
//        myVC.isHiddenNavBack = YES;
//        [self.navigationController pushViewController:myVC animated:YES];
//    }
    
  
    if ([userId isEqualToString:@"贴脸儿小助手"]) {
        
        return;
    }
    if([userId isEqualToString:[HQHttpManager getUserId]]){
//        YD_MyPersionalInfoVC2 *vc = [YD_MyPersionalInfoVC2 new];
//        [self.navigationController pushViewController:vc animated:YES];
    }else{
        HomeStrangCollionViewController *UDIVC = [[HomeStrangCollionViewController alloc] init];
        UDIVC.UserId = userId;
        [self.navigationController pushViewController:UDIVC animated:YES];
    }
}
#pragma mark 懒加载
- (UILabel *)nameLabel {
    if (!_nameLabel) {
        _nameLabel = [UILabel new];
        _nameLabel.textAlignment = NSTextAlignmentCenter;
        _nameLabel.font = [UIFont systemFontOfSize:16];
        _nameLabel.textColor = [UIColor whiteColor];
        _nameLabel.text = @"加载中";
        
    }
    return _nameLabel;
}
- (UILabel *)placeLabel {
    if (!_placeLabel) {
        _placeLabel = [UILabel new];
        _placeLabel.textAlignment = NSTextAlignmentCenter;
        _placeLabel.font = [UIFont systemFontOfSize:12];
        _placeLabel.textColor = [UIColor whiteColor];
        _placeLabel.text = @"加载中";
    }
    return _placeLabel;
}
//点击消息内容
- (void)didTapMessageCell:(RCMessageModel *)model{
    RCLocationMessage * locationM = (RCLocationMessage*)model.content;
    if([model.objectName isEqualToString:@"RC:LBSMsg"]){
        if(locationM){
            [self presentLocationViewController:locationM];
        }
    }
    if([model.objectName isEqualToString:@"RC:ImgMsg"]){
       
        [self  presentImagePreviewController:model];
        
    }
    if ([model.objectName isEqualToString:@"app:custom"]) {
        HRMessage *message = (HRMessage *)model.content;
        [HQHttpManager receiveGiftWithUserGiftId:message.userGiftId successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
            if (isSuccess) {
                [self sendMessage:[RCTextMessage messageWithContent:message.answer] pushContent:@"answer"];
            }
        }];
    }
    if ([model.objectName isEqualToString:@"app:GiftMessage"]) {
        UserEarningsController *vc = [UserEarningsController new];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
//****************赠送礼物*****************
- (void)pluginBoardView:(RCPluginBoardView *)pluginBoardView clickedItemWithTag:(NSInteger)tag {
    if (tag == 101) {
        if (!_giftView) {
            _giftView = [[HRGiftView alloc] initWithFrame:CGRectMake(0, KScreenHeight-pluginBoardView.frame.size.height, KScreenWidth, pluginBoardView.frame.size.height)];
            //0不展示增长时间
            _giftView.timeType = @"0";
            [self.view addSubview:_giftView];
            _giftView.delegate = self;
        }
        _giftView.isShow = NO;
        
        
    }else {
        [super pluginBoardView:pluginBoardView clickedItemWithTag:tag];
    }
}
- (void)updateForSharedMessageInsertSuccess:(NSNotification *)notification {
    RCMessage *message = notification.object;
    if (message.conversationType == self.conversationType &&
        [message.targetId isEqualToString:self.targetId]) {
        [self appendAndDisplayMessage:message];
    }
}

- (void)didSendMessage:(NSInteger)stauts
               content:(RCMessageContent *)messageCotent{

    if ([self.targetId isEqualToString:@"贴脸儿小助手"]) {
        self.chatSessionInputBarControl.hidden = NO;
        
    }else{
        [CheekVodeRequest getCheekVideoisFriendUid:[HQHttpManager getUserId]
                                               Wid:self.targetId success:^(id sucess) {
                                                   
                                                   _model = [CheekisFriendModel mj_objectWithKeyValues:sucess[@"res"]];
                                                   if ([_model.status isEqualToString:@"0"]) {
                                                       
                                                       [CheekVodeRequest getCheekFriendhasTalkUid:[HQHttpManager getUserId] Wid:self.targetId success:^(id sucess) {
                                                           
                                                           
                                                           self.chatSessionInputBarControl.hidden = YES;
                                                           _button = [UIButton buttonWithType:UIButtonTypeCustom];
                                                           _button.frame =CGRectMake(0, self.conversationMessageCollectionView.bottom, KScreenWidth, 50);
                                                           [_button setImage:[UIImage imageNamed:@"message_chat_wait_icon"] forState:UIControlStateNormal];
                                                           [_button setTitle:@"等待对方添加你为好友" forState:UIControlStateNormal];
                                                           _button.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
                                                           [_button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                                                           _button.backgroundColor = [UIColor whiteColor];
                                                           [self.view addSubview:_button];
                                                           [self.conversationMessageCollectionView reloadData];
                                                           
                                                           
                                                       } failure:^(NSError *error) {
                                                           
                                                       }];
                                                   }else{
                                                       _button.hidden = YES;
                                                       self.chatSessionInputBarControl.hidden = NO;
                                                       [self.conversationMessageCollectionView reloadData];
                                                       
                                                       
                                                   }
                                                   
                                               } failure:^(NSError *error) {
                                                   
                                               }];

    }
    
    
    
    

    
    
    
}
#pragma mark ==========赠送=========
- (void)didClickSendButton:(CheekGiftModel *)gift {
    NSLog(@"gift=%@",gift);
    _giftView.isShow = YES;
    CheekGiftModel *giftmodel = gift;

    [HcardHttpmanager giveGiftWithWid:self.targetId WithGiftId:giftmodel.giftId WithStatus:@"2" WithAskId:nil Success:^(id result) {
        
        NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
        [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
        NSNumber *numTemp = [numberFormatter numberFromString:giftmodel.charm];

        [self sendMessage:[HRGiftMessage messageWithContent:[NSString stringWithFormat:@"您送给对方%@x1,您收到礼物%@x1  +%@魅力值,%@,%@", giftmodel.name,giftmodel.name,giftmodel.charm,giftmodel.img,[HQHttpManager getUserId]] charm:numTemp ] pushContent:@"app:GiftMessage"];
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark ============充值==============
- (void)didClickRechargeButton {
    UserAccountViewController *VC = [[UserAccountViewController alloc] init];
    [self.navigationController pushViewController:VC animated:YES];
}
#pragma mark==============键盘收起展开=============
- (void)chatInputBar:(RCChatSessionInputBarControl *)chatInputBar shouldChangeFrame:(CGRect)frame {
    

    if (frame.size.height == KScreenHeight - frame.origin.y) {
        _giftView.isShow = YES;
    }
}
- (void)keyboardWillShow:(NSNotification *)note{
    _giftView.isShow = YES;
}

- (void)keyboardWillHide:(NSNotification *)note{
    
}

- (void)onPublicServiceMenuItemSelected:(RCPublicServiceMenuItem *)selectedMenuItem {
    NSLog(@"..公众号被点击..");
}

#pragma mark - 定位
-(void)didLocation{
    if ([CLLocationManager locationServicesEnabled]) {
        //定位功能可用，开始定位
        self.locationManger = [[CLLocationManager alloc] init];
        self.locationManger.delegate = self;
        if ([[[UIDevice currentDevice] systemVersion] floatValue]  >= 8.0) {
            //使用期间
            [self.locationManger requestWhenInUseAuthorization];
            //始终
            //or [self.locationManage requestAlwaysAuthorization]
        }
        [self.locationManger startUpdatingLocation];
    }else{
        //        [self displayMessage:@"定位功能不可用,请打开定位功能"];
    }
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            if ([self.locationManger respondsToSelector:@selector(requestAlwaysAuthorization)])
            {
                [self.locationManger requestWhenInUseAuthorization];
            }
            break;
        default:
            break;
    }
    
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    //   NSLog(@"error");
    //  [self getFriendInfo];
      [[DMCAlertCenter defaultCenter] postAlertWithMessage:@"定位失败，请重新定位"];
}

// 6.0 以上调用这个函数
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    isFrist++;
    CLLocation *newLocation = locations[0];
    CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;
    longitude = @(oldCoordinate.longitude).stringValue;
    latitude = @(oldCoordinate.latitude).stringValue;
//    NSLog(@"旧的经度：%f,旧的纬度：%f",oldCoordinate.longitude,oldCoordinate.latitude);
    [self.locationManger stopUpdatingLocation];
    if (isFrist ==1) {
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        [geocoder reverseGeocodeLocation:newLocation
                       completionHandler:^(NSArray *placemarks, NSError *error){
                           for (CLPlacemark *place in placemarks) {
                               address = place.locality;
                           }
                           if (address&&latitude&&latitude&&!KCNSSTRING_ISEMPTY([HQHttpManager getUserId])&&!KCNSSTRING_ISEMPTY([HQHttpManager getUserToken])) {
                               // [self getFriendInfo];
                           }
                           
                       }];
    }
    
}

// 6.0 调用此函数
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    [self.locationManger stopUpdatingLocation];
    isFrist++;
    if (isFrist ==1) {
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        [geocoder reverseGeocodeLocation:newLocation
                       completionHandler:^(NSArray *placemarks, NSError *error){
                           for (CLPlacemark *place in placemarks) {
                               NSLog(@"%@",place.addressDictionary);
                               address = place.locality;
                           }
                           if (address&&latitude&&latitude&&!KCNSSTRING_ISEMPTY([HQHttpManager getUserId])&&!KCNSSTRING_ISEMPTY([HQHttpManager getUserToken])) {
                               //                               [self getFriendInfo];
                           }
                           
                       }];
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}







@end
